package cn.com.dhcc.ddi.task.dao;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.com.dhcc.app.core.dao.BaseDao;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.pub.CM;
import cn.com.dhcc.app.pub.core.tag.staticcode.StaticCode;
import cn.com.dhcc.ddi.task.vo.Task;
import cn.com.dhcc.ddi.task.vo.wapper.TaskRowWapper;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

/**
 * TaskDao
 * @日期：2016/11/10 17:21
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Repository
public class TaskDao extends BaseDao {
    private static Logger logger = Log.getLogger(Log.LOGTYPE.DDI);

    /**
     * 获取对象
     * @param id
     * @return
     * @throws DaoException
     */
    public Task get(String id) throws DaoException {
        return getDao().getModuleById("获取对象",Task.class,new Object[]{id});
    }

    /**
     * 新增
     * @param obj
     * @return
     * @throws DaoException
     */
    public int insert(Task obj) throws DaoException {
        return getDao().insertModule("新增",obj);
    }

    /**
     * 修改
     * @param obj
     * @return
     * @throws DaoException
     */
    public int update(Task obj) throws DaoException {
        return getDao().updateModuleByIdExecuteNull("修改",obj);
    }
    
    public List<Task> list(WhereCondition condition) throws DaoException {
    	return getDao().listModule("获取全部任务列表", Task.class, condition);
    }
    
    /**
     * 新增
     * @param obj
     * @return
     * @throws DaoException
     */
    public int delete(Task obj) throws DaoException {
        return getDao().deleteModuleById("删除任务", obj);
    }
    
    public int deleteById(String id) throws DaoException {
    	String sql = "DELETE FROM " + SI_TABLE("t_ddi_task") + " WHERE id=?";
    	return getDao().delete("根据任务id删除任务", sql, new Object[]{id});
    }

    /**
     * 新增或修改
     * @param obj
     * @return
     * @throws DaoException
     */
    public int insertOrUpdate(Task obj) throws DaoException {
        return getDao().saveOrUpdateModuleByIdExecuteNull("新增或修改",obj);
    }
    
   
    /**
     * 获取一次性任务分页列表
     * @param pager
     * @param searchData
     * @return
     * @throws DaoException
     */
    public PagerData<Task> getOnTimePagerList(Pager pager, WhereCondition searchData) throws DaoException {
    	String msg;
		String sql = "select t1.*,t3.execute_type,t3.execute_time, t5.execute_begin_time, t5.execute_end_time from  " + SI_TABLE("t_ddi_task")+" t1"
							+"  left join " + SI_TABLE("t_ddi_task_ontime")+" t3 on t1.id = t3.task_id "
							+"  LEFT JOIN (SELECT t4.TASK_ID, t4.ID, t4.LOG_STATUS, COUNT(t4.id) AS COUNT,"
							+"  MAX(t4.LINKSTARTTIME) AS execute_begin_time, "
							+"  MAX(t4.LINKENDTIME) AS execute_end_time FROM " 
							+SI_TABLE("t_ddi_task_log") + " t4" + " WHERE t4.group_id IS NULL GROUP BY t4.task_id) t5"
							+"  ON t1.ID = t5.TASK_ID"
							+"  WHERE t1.task_freq_type= '1' and t1.status in ('1','2','3','5')";
		try {
			return getDao().getPagerList("获取一次性任务分页列表", sql, new TaskRowWapper(),pager, searchData,new Object[]{});
		} catch (DaoException e) {
			msg = "获取一次性任务分页列表失败";
			logger.error(msg, e);
			throw new DaoException(msg, e);
		}
    }
    
    /**
     * 获取周期性任务分页列表
     * @param searchData
     * @return
     * @throws DaoException
     */
	public PagerData<Task> getPeriodPagerList(Pager pager, WhereCondition searchData) throws DaoException{
		String sql = "SELECT t1.id,"
						+"	t1.task_name,"
						+"	t1.task_freq_type,"
				       	+"	t1.mtime,t1.status,"
				       	+"	t3.freq,"
				       	+"	t3.interval_vallue,"
				       	+"	t3.execute_time,"
				       	+"  COALESCE(t7.success, 0) AS successCount,"
				       	+"	t5.execute_begin_time,"
				       	+"	t5.execute_end_time,"
				       	+"	t5.count,"
				       	+"  t5.LOG_STATUS"
					    +"	FROM  " + SI_TABLE("t_ddi_task")+"  t1"
					    +"	LEFT JOIN  " + SI_TABLE("t_ddi_task_period")+"  t3"
					    +"		on t1.id = t3.task_id"
					    +"  LEFT JOIN   " + " (select t6.TASK_ID, COUNT(*) AS success FROM " + SI_TABLE("t_ddi_task_log") + " t6"
					    +"  WHERE t6.LOG_STATUS = '1' AND group_id IS NULL group by t6.TASK_ID) t7"
					    +"  ON t1.ID = t7.TASK_ID"
					    +"  LEFT JOIN   " + "(SELECT t4.TASK_ID, t4.ID, t4.LOG_STATUS, COUNT(t4.id) AS COUNT,"
					    +"  MAX(t4.LINKSTARTTIME) AS execute_begin_time, "
					    +"  MAX(t4.LINKENDTIME) AS execute_end_time FROM " 
					    +SI_TABLE("t_ddi_task_log") + " t4" + " WHERE t4.group_id IS NULL AND t4.`LOG_STATUS` = '1'"
					    +"  GROUP BY t4.task_id) t5"
					    +"  ON t1.ID = t5.TASK_ID"
					    +"	WHERE t1.task_freq_type = '2' and t1.status in ('1','2','3','5')";
		try {	
			return getDao().getPagerList("获取周期性任务分页列表", sql, new TaskRowWapper(), pager, searchData,new Object[]{});
		} catch (DaoException e) {
			throw new DaoException(e);
		}
	}
	
	public List<Task> getPeriodList(WhereCondition searchParameter) throws DaoException {
		String sql = " SELECT * FROM " + SI_TABLE("t_ddi_task") + " t1 "
				   + " WHERE TASK_FREQ_TYPE='2' AND STATUS in ('1','2','3','5')";
		try {	
			return getDao().listModule("获取周期性任务列表", sql, Task.class, searchParameter);
		} catch (DaoException e) {
			throw new DaoException(e);
		}
	}
	
	
	
	/**
	 * 获取历史任务分页列表
	 * @param pager
	 * @param searchData
	 * @return
	 * @throws DaoException
	 */
	public PagerData<Task> getHistoryList(Pager pager, WhereCondition searchData) throws DaoException {
		String msg;
		String sql = "select " 
						+"	t1.task_name,"
						+"	t1.id,"
						+"	t1.task_freq_type,"
				       	+"	t1.mtime,"
				       	+"	t3.execute_begin_time,"
				       	+"  t3.execute_end_time,"
				       	+"	t3.count,"
				       	+"	t3.LOG_STATUS"
				       	+"	FROM  " + SI_TABLE("t_ddi_task") +" t1"
				        +"  LEFT JOIN   " + "(SELECT t2.TASK_ID, t2.LOG_STATUS, t2.ID, COUNT(t2.id) AS COUNT, "
				        +"	MAX(t2.LINKSTARTTIME) AS execute_begin_time,"
				        +"  MAX(t2.LINKENDTIME) AS execute_end_time FROM " 
					    +SI_TABLE("t_ddi_task_log") + " t2" + " WHERE t2.group_id IS NULL GROUP BY t2.task_id) t3"
					    +"  ON t1.ID = t3.TASK_ID";
					   
		try {
			return CM.getDao().getPagerList("获取历史任务", sql, new TaskRowWapper(),pager,searchData,new Object[]{});
		} catch (DaoException e) {
			msg = "获取历史任务失败";
			logger.error(msg, e);
			throw new DaoException(msg, e);
		}
	}
	
	public boolean isPropertyUnique(String property, String newValue,
			String oldValue) throws DaoException {
		if (newValue.equals(oldValue)) {
			return true;
		}
		final String sql = "select * from " + SI_TABLE("t_ddi_task")
				+ " where  " + property + "=? and status  <> '4'  ";
		try {
			List<Task> list = CM.getDao().list("验证唯一", sql, new TaskRowWapper(), new Object[] { newValue });
			if (list.size() == 0)
				return true;
		} catch (DaoException e) {
			throw new DaoException("验证唯一失败！", e);
		}
		return false;
	}
	
	/**
	 * 批量删除任务
	 * @param ids 任务id列表
	 * @throws DaoException 
	 */
	public int batchDeleteById(String[] ids) throws DaoException {
		try {
			List<Object[]> params = new ArrayList<Object[]>();
			for (String id : ids) {
				params.add(new Object[] { id });
			}
			 
			String sql = "DELETE FROM " + SI_TABLE("t_ddi_node_info") + " WHERE id=?";
			return CM.getDao().batchDelete("批量删除任务", sql, params);
		} catch (DaoException e) {
			throw new DaoException("批量删除任务失败！", e);
		}
	}
	
	public List<Task> getTimedPeriodTaskList() throws DaoException {
		try {
			String sql = "SELECT t1.id, t1.task_name, t2.START_TIME AS EXECUTE_TIME, t2.EXECUTE_TYPE, t4.count FROM "
					+ " (SELECT * FROM " + SI_TABLE("t_ddi_task") + " WHERE TASK_FREQ_TYPE='2') t1 "
					+ " LEFT JOIN " + SI_TABLE("t_ddi_task_period") + " t2 "
			        + " ON t1.id = t2.task_id "
			        + " LEFT JOIN (SELECT t3.task_id, count(t3.id) as count FROM " + SI_TABLE("t_ddi_task_log") + " t3 "
			        + " WHERE group_id IS NULL GROUP BY t3.task_id) t4 ON t1.id = t4.task_id "
			        + " WHERE t2.EXECUTE_TYPE='3' AND t4.count IS NULL AND t2.`START_TIME` <= NOW()";
			return CM.getDao().list("获取周期性定时任务列表", sql, new TaskRowWapper(), new Object[] {});
		} catch (DaoException e) {
			throw new DaoException("获取周期性定时任务列表失败", e);
		}
	}
	
	public List<Task> getTimedOntimeTaskList() throws DaoException {
		try {
			String sql = "SELECT t1.id, t1.task_name, t1.status, t2.EXECUTE_TIME, t2.EXECUTE_TYPE FROM "
					+ " (SELECT * FROM " + SI_TABLE("t_ddi_task") + " WHERE TASK_FREQ_TYPE='1') t1 "
					+ " LEFT JOIN " + SI_TABLE("t_ddi_task_ontime") + " t2 "
			        + " ON t1.id = t2.task_id "
			        + " WHERE t2.EXECUTE_TYPE='3' AND t1.status = '1' AND t2.`EXECUTE_TIME` <= NOW()";
			return CM.getDao().list("获取周期性定时任务列表", sql, new TaskRowWapper(), new Object[] {});
		} catch (DaoException e) {
			throw new DaoException("获取周期性定时任务列表失败", e);
		}
	}

	public List<Task> getTasks(WhereCondition condition) throws DaoException{
		try {
			return CM.getDao().listModule("获取etl任务", Task.class, condition);
		} catch (DaoException e) {
			throw new DaoException(e);
		}
	}

	public List<Task> getSettTasks() throws DaoException{
		Calendar startDate = Calendar.getInstance();
		Date now = new Date();

		startDate.setTime(now);
		startDate.add(Calendar.DAY_OF_MONTH, -1);
		startDate.set(Calendar.HOUR_OF_DAY,0);
		startDate.set(Calendar.MINUTE,0);
		startDate.set(Calendar.SECOND,0);

		Calendar endDate = Calendar.getInstance();
		endDate.setTime(now);
		endDate.add(Calendar.DAY_OF_MONTH, -1);
		endDate.set(Calendar.HOUR_OF_DAY,23);
		endDate.set(Calendar.MINUTE,59);
		endDate.set(Calendar.SECOND,59);

		String sql = "select * from " + SI_TABLE("t_ddi_task")+" where task_freq_type=? and is_sett='1' and id in (select distinct task_id from " + SI_TABLE("t_ddi_task_log")+" t where t.linkstarttime >=? and t.linkstarttime <=?)";
		try {
			return CM.getDao().list("获取周期性任务", sql, new TaskRowWapper(),new Object[]{StaticCode.TASK_FREQ_TYPE.PERIOD.getCode(),startDate.getTime(),endDate.getTime()});
		} catch (DaoException e) {
			throw new DaoException(e);
		}
	}
}
